﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
    using System.Data.SqlClient;


namespace SimpleConnectToDb
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //How to connect to Data Base?
            const string ConnectionString = "Data Source=.;Initial Catalog=Simple;Integrated Security=True";

            //Connection to Data Base
            SqlConnection connection = new SqlConnection(ConnectionString);

            //Sql Query - Insert
            SqlCommand command = new SqlCommand("INSERT INTO Names(name) VALUES (@Name)");

            //Name parameter
            command.Parameters.AddWithValue("@Name", txtName.Text);

            //Connection for query
            command.Connection = connection;
            
            //Connect to Data Base
            connection.Open();
            
            //Run query - Add Record
            command.ExecuteNonQuery();

            //Disconnect from Data Base
            connection.Close();

            //Clear TextBox for next name
            txtName.Text = "";
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //How to connect to Data Base?
            const string ConnectionString = "Data Source=.;Initial Catalog=Simple;Integrated Security=True";

            //Connection to Data Base
            SqlConnection connection = new SqlConnection(ConnectionString);

            //Sql Query - Select whole table
            SqlCommand command = new SqlCommand("SELECT * FROM Names");

            //Connection for query
            command.Connection = connection;

            //Connect to Data Base
            connection.Open();

            //Handle filling tanle
            SqlDataAdapter adapter = new SqlDataAdapter(command);

            //In-Memory Table for Names table
            DataTable table = new DataTable();

            //Fill table with Names
            adapter.Fill(table);

            //Show Names to DataGridView
            dgNames.DataSource = table;

            //Disconnect from Data Base
            connection.Close();
        }
    }
}
